package com.example.kehoobackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.kehoobackend.common.CommentType;
import com.example.kehoobackend.common.CommonResponse;
import com.example.kehoobackend.common.FollowType;
import com.example.kehoobackend.common.LikeType;
import com.example.kehoobackend.domain.*;
import com.example.kehoobackend.persistance.LikeMapper;
import com.example.kehoobackend.persistance.QuestionMapper;
import com.example.kehoobackend.service.CommentService;
import com.example.kehoobackend.service.DayInfoService;
import com.example.kehoobackend.service.FollowService;
import com.example.kehoobackend.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {


    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    LikeMapper likeMapper;

    @Autowired
    CommentService commentService;

    @Lazy
    @Autowired
    FollowService followService;

    @Lazy
    @Autowired
    DayInfoService dayInfoService;


    @Override
    public boolean deleteQuestion(Integer question_id) {
         removeById(question_id);

         //删除问题下的所有评论
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("to_id",question_id).eq("type", CommentType.QUESTION).select("comment_id");
        List<Comment> comments = commentService.list(commentQueryWrapper);
        for(Comment comment : comments){
            commentService.removeById(comment);
        }

        //删除对问题的所有关注
        QueryWrapper<Follow> followQueryWrapper = new QueryWrapper<>();
        followQueryWrapper.eq("to_id",question_id).eq("type", FollowType.QUESTION);
        List<Follow> followList = followService.list(followQueryWrapper);
        for(Follow follow : followList){
            followService.removeById(follow);
        }

        return true;
    }

    @Override
    public Question addQuestion(Question question, List<Integer> topic_ids) {
        if(save(question)){
            int question_id = question.getQuestion_id();
            for(Integer topic_id : topic_ids){
                questionMapper.insertIntoQuestionTopic(question_id,topic_id);
            }

            Integer new_question_id = question.getQuestion_id();
            Question newQuestion = getById(new_question_id);

            //今日新增问题数加1
            String currentDate = String.valueOf(LocalDate.now());
            DayInfo dayInfo = dayInfoService.getById(currentDate);
            dayInfo.setNew_questions_count(dayInfo.getNew_questions_count()+1);
            dayInfoService.updateById(dayInfo);


            return newQuestion;
        }
        else return null;
    }

    @Override
    public CommonResponse<List<Question>> getQuestionByTopicId(Integer current_id,Integer topic_id) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("topic_id",topic_id);
        List<Integer> question_ids = questionMapper.listQuestionIdByTopicId(topic_id);
        List<Question> questions = new ArrayList<>();
        for(Integer question_id : question_ids){
            questions.add(getById(question_id));
        }
        setIsLiked(current_id,questions);
        return CommonResponse.createForSuccess("查询话题所有问题",questions);
    }

    @Override
    public CommonResponse<List<Question>> getAllQuestion(Integer current_id) {
        List<Question> questions = list();
        setIsLiked(current_id,questions);
        return CommonResponse.createForSuccess("查询所有问题",questions);
    }

    //TODO:搜索引擎？
    @Override
    public CommonResponse<List<Question>> getQuestionByKeyword(Integer current_id,String keyword) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("question_title",keyword);
        List<Question> questions = list(queryWrapper);
        setIsLiked(current_id,questions);
        return CommonResponse.createForSuccess("查询标题中含有关键字的问题",questions);
    }

    @Override
    public CommonResponse<List<Question>> getQuestionForHome(Integer current_id,String order_type, Integer start, Integer limit) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        boolean flag = true;
        //order_type为latest或hot
        if(order_type.equals("latest")){
            queryWrapper.orderByDesc("create_time");
            flag = false;
        }else if(order_type.equals("hot")){
            queryWrapper.orderByDesc("liked_count");
        }else return CommonResponse.createForError("错误：不存在的order_type");

        List<Question> questions = list(queryWrapper);
        if(questions.isEmpty())return CommonResponse.createForSuccess("暂无问题",questions);

        List<Question> resultQuestions = new ArrayList<>();
        while (limit > 0){
            if(start>questions.size()-1){
                break;
            }
            resultQuestions.add(questions.get(start));
            start++;
            limit--;
        }

        setIsLiked(current_id,resultQuestions);
        return flag ? CommonResponse.createForSuccess("查询最热问题",resultQuestions)
                : CommonResponse.createForSuccess("查询最新问题",resultQuestions);
    }

    @Override
    public CommonResponse<List<Question>> getQuestionForCollect(Integer current_id,String order_type, Integer user_id, Integer start, Integer limit) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        boolean flag = true;
        queryWrapper.eq("user_id",user_id);
        //order_type为latest或hot
        if(order_type.equals("latest")){
            queryWrapper.orderByDesc("create_time");
            flag = false;
        }else if(order_type.equals("hot")){
            queryWrapper.orderByDesc("liked_count");
        }else return CommonResponse.createForError("错误：不存在的order_type");

        List<Question> questions = list(queryWrapper);
        if(questions.isEmpty())return CommonResponse.createForSuccess("暂无问题",questions);

        List<Question> resultQuestions = new ArrayList<>();
        while (limit > 0){
            if(start>questions.size()-1){
                break;
            }
            resultQuestions.add(questions.get(start));
            start++;
            limit--;
        }

        setIsLiked(current_id,resultQuestions);
        return flag ? CommonResponse.createForSuccess("查询关注的用户提出的最热问题",resultQuestions)
                : CommonResponse.createForSuccess("查询关注的用户提出的最新问题",resultQuestions);
    }

    @Override
    public CommonResponse<List<Question>> getQuestionByLikeDesc(Integer current_id,Integer start, Integer limit) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("liked_count");
        List<Question> questions = list(queryWrapper);
        if(questions.isEmpty())return CommonResponse.createForSuccess("暂无问题",questions);

        List<Question> resultQuestions = new ArrayList<>();
        while (limit > 0){
            if(start>questions.size()-1){
                break;
            }
            resultQuestions.add(questions.get(start));
            start++;
            limit--;
        }

        setIsLiked(current_id,resultQuestions);
        return CommonResponse.createForSuccess("按点赞数降序查询问题",resultQuestions);
    }

    @Override
    public CommonResponse<List<Question>> getQuestionByUserId(Integer user_id) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user_id);
        return CommonResponse.createForSuccess("查询用户提出的问题",list(queryWrapper));
    }

    @Override
    public boolean like(Integer question_id, Integer user_id) {
        //存储点赞关系
        Question question = getById(question_id);
        question.setLiked_count(question.getLiked_count()+1);
        if(updateById(question)){
            Like like = new Like();
            like.setUser_id(user_id);
            like.setTarget_id(question_id);
            like.setType(LikeType.QUESTION);

            //TODO:确定返回值是多少
            likeMapper.insert(like);
            return true;
        }else return false;
    }

    @Override
    public boolean cancelLike(Integer question_id, Integer user_id) {
        QueryWrapper<Like> likeQueryWrapper = new QueryWrapper<>();
        //删除点赞关系
        Question question = getById(question_id);
        question.setLiked_count(question.getLiked_count()-1);
        if(updateById(question)){
            likeQueryWrapper.eq("user_id",user_id).eq("target_id",question.getQuestion_id())
                    .eq("type",LikeType.QUESTION);
            return likeMapper.delete(likeQueryWrapper) == 1;
        }else return false;
    }

    @Override
    public boolean isLike(Integer question_id, Integer user_id) {
        QueryWrapper<Like> likeQueryWrapper = new QueryWrapper<>();
        likeQueryWrapper.eq("user_id",user_id)
                .eq("target_id",question_id).eq("type", LikeType.QUESTION);
        Like like = likeMapper.selectOne(likeQueryWrapper);
        return like != null;
    }

    @Override
    public CommonResponse<Question> getQuestionDetail(Integer question_id) {
        return CommonResponse.createForSuccess("获取问题详情",getById(question_id));
    }

    @Override
    public Integer getUserIdByQuestionId(Integer question_id) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id",question_id).select("user_id");
        Question question = getOne(queryWrapper);
        return question.getUser_id();
    }

    @Override
    public CommonResponse<List<Question>> getAllQuestion1() {
        return CommonResponse.createForSuccess("管理员查询所有问题",list());
    }

    public void setIsLiked(Integer current_id,List<Question> questions){
        for(Question question : questions){
            question.set_liked(isLike(question.getQuestion_id(),current_id));
        }
    }
}
